package sz.szsmk.citizencard.ui.activity;

import android.os.Bundle;
import androidx.core.view.ViewCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.chenenyu.router.annotation.Route;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.google.android.flexbox.FlexboxLayout;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

import sz.szsmk.citizencard.DaggerApplication;
import sz.szsmk.citizencard.R;
import sz.szsmk.citizencard.databinding.SearchActivityBinding;
import sz.szsmk.citizencard.db.Note;
import sz.szsmk.citizencard.db.NoteDao;
import sz.szsmk.citizencard.dialog.TwoButtonDialog;
import sz.szsmk.citizencard.ioc.Compontent.DaggerCommonActivityComponent;
import sz.szsmk.citizencard.log.L;
import sz.szsmk.citizencard.model.network.bean.Book;
import sz.szsmk.citizencard.model.network.bean.response.SearchViewResponse;
import sz.szsmk.citizencard.mvp.contract.ISearchContact;
import sz.szsmk.citizencard.mvp.presenter.SearchPresenter;
import sz.szsmk.citizencard.ui.adapter.HomePageAdapter;
import sz.szsmk.citizencard.ui.adapter.SearchViewAdapter;
import sz.szsmk.citizencard.ui.base.IBaseActivity;
import sz.szsmk.citizencard.ui.fragment.SearchHotelFragment;
import sz.szsmk.citizencard.ui.fragment.SearchViewFragment;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.JumpUtils;
import sz.szsmk.citizencard.util.PubUtils;
import sz.szsmk.citizencard.util.Util;
import sz.szsmk.citizencard.widget.NoScrollViewPager;

/**
 * Copyright (c)2018
 * author: zdh
 * created on: 2018/7/13 9:39
 * description:亲子休闲搜索页面
 */
@Route("search")
public class SearchActivity extends IBaseActivity<SearchPresenter, SearchActivityBinding>
        implements ISearchContact.ISearchView, OnTabSelectListener, View.OnClickListener {

    private FlexboxLayout flexboxLayout;
    String[] tags = {"同里古镇", "阳山温泉", "温泉度假村", "长文字的搜索历史长文字的搜索历史", "古镇客栈"};
    private ArrayList<Fragment> mFragments = new ArrayList<>();

    private NoScrollViewPager searchVp;
    private SearchViewAdapter searchViewAdapter;

    private List<SearchViewResponse.SpotDeatilHotelListBean> hotelListBean = new ArrayList<>();
    private List<SearchViewResponse.SpotDeatilHotelListBean> spotListBean = new ArrayList<>();
    //    private List<SearchViewResponse.SpotDeatilSpotListBean> spotListBean = new ArrayList<>();
    private RecyclerView searchViewRv;
    private NoteDao noteDao;
    private List<Note> notes;
    private String keyWord;
    private String value;

    @Override
    protected int attachLayoutRes() {
        return R.layout.search_activity;
    }

    @Override
    protected void initInjector() {
        DaggerCommonActivityComponent.builder().appCompontent(DaggerApplication.getAppComponent())
                .build().inject(this);
    }

    @Override
    protected void initViews() {
        flexboxLayout = (FlexboxLayout) findViewById(R.id.flexbox_layout);
        dataBinding.titleLayout.settingTitle.setText("搜索");
        noteDao = DaggerApplication.getmDaoSession().getNoteDao();
        searchVp = dataBinding.searchVp;

        value = getIntent().getStringExtra("value");
        dataBinding.searchView.setOnClickListener(this);
        dataBinding.searchHotel.setOnClickListener(this);
        dataBinding.serAllSer.setOnClickListener(this);
        dataBinding.titleLayout.back.setOnClickListener(this);
        dataBinding.searchDel.setOnClickListener(this);
        dataBinding.queryBtn.setOnClickListener(this);

        dataBinding.searchEt.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                    String keyWord = dataBinding.searchEt.getText().toString();
                    if (TextUtils.isEmpty(keyWord)) {
                        PubUtils.popTipOrWarn(SearchActivity.this, "您未输入任何内容");
                    } else {
                        insertData(keyWord);
                    }
                    return true;
                }
                return false;
            }
        });
        setRvData();
        mFragments.add(SearchViewFragment.getInstance());
        mFragments.add(SearchHotelFragment.getInstance());
        HomePageAdapter myPagerAdapter = new HomePageAdapter(getSupportFragmentManager(), mFragments);
        searchVp.setAdapter(myPagerAdapter);
        searchVp.setCurrentItem(0);

    }

    private void setRvData() {
        searchViewRv = dataBinding.searchViewRv;
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        searchViewRv.setLayoutManager(linearLayoutManager);
        searchViewAdapter = new SearchViewAdapter(this);
        searchViewRv.setAdapter(searchViewAdapter);

    }

    @Override
    protected void updateViews() {

    }

    @Override
    public void onTabSelect(int position) {

    }

    @Override
    public void onTabReselect(int position) {

    }

    @Override
    protected void onResume() {
        super.onResume();
        reFreshData();
    }

    public void reFreshData() {

        notes = noteDao.loadAll();
        if (notes != null) {
            if (notes.size() == 0){
                dataBinding.noLog.setVisibility(View.VISIBLE);
            }else {
                dataBinding.noLog.setVisibility(View.GONE);
            }
                flexboxLayout.removeAllViews();
                for (int i = 0; i < this.notes.size(); i++) {
                    String mLog = notes.get(i).getName() + "";
                    L.e(Constant.TAG, "数据库查询：" + mLog);
                    Book book = new Book();
                    book.setName(mLog);
                    flexboxLayout.addView(createNewFlexItemTextView(book));
                }
        }
    }

    /**
     * 动态创建TextView
     *
     * @param book
     * @return
     */
    private TextView createNewFlexItemTextView(final Book book) {
        final TextView textView = new TextView(this);
        textView.setGravity(Gravity.CENTER);
        textView.setText(book.getName());
        textView.setTextSize(12);
        textView.setTextColor(getResources().getColor(R.color.color_99a3a8));
        textView.setBackgroundResource(R.drawable.search_history_bg);
        textView.setTag(book.getName());
        textView.setMaxLines(1);
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.e(Constant.TAG, book.getName());
            }
        });
        int padding = Util.dpToPixel(this, 4);
        int paddingLeftAndRight = Util.dpToPixel(this, 8);
        ViewCompat.setPaddingRelative(textView, paddingLeftAndRight, padding, paddingLeftAndRight, padding);
        FlexboxLayout.LayoutParams layoutParams = new FlexboxLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        int margin = Util.dpToPixel(this, 6);
        int marginTop = Util.dpToPixel(this, 16);
        layoutParams.setMargins(margin, marginTop, margin, 0);
        textView.setLayoutParams(layoutParams);
        textView.setOnTouchListener(new View.OnTouchListener() {

            private String mCard;

            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    Log.i("zhong", "onTouch: motionEventX : " + motionEvent.getX() + " viewWidth :" + view.getWidth());
                    if (motionEvent.getX() < view.getWidth() - view.getHeight() * 0.6) {
                        mCard = textView.getText().toString();
                        dataBinding.searchEt.setText(mCard);
                    } else {
                        String cardId = (String) view.getTag();
                        for (Note dao : notes) {
                            if (dao.getName().equals(cardId)) {
                                noteDao.delete(dao);
                                break;
                            }
                        }
                        reFreshData();
                    }
                }
                return false;
            }
        });
        return textView;
    }

    @Override
    public void updataError(String message) {

    }

    @Override
    public void updataSuccess(SearchViewResponse response) {
        List<SearchViewResponse.SpotDeatilHotelListBean> spot_deatil_hotel_list = response.getSpot_deatil_hotel_list();
        if (spot_deatil_hotel_list != null) {
            hotelListBean = spot_deatil_hotel_list;
        }

        List<SearchViewResponse.SpotDeatilSpotListBean> spot_deatil_spot_list = response.getSpot_deatil_spot_list();
        if (spot_deatil_spot_list != null) {
            ArrayList<SearchViewResponse.SpotDeatilHotelListBean> listBeans = new ArrayList<>();
            for (int i = 0; i < spot_deatil_spot_list.size(); i++) {
                SearchViewResponse.SpotDeatilSpotListBean spotDeatilSpotListBean = spot_deatil_spot_list.get(i);
                String json = new Gson().toJson(spotDeatilSpotListBean);
                SearchViewResponse.SpotDeatilHotelListBean hotelListBean1 = new Gson().fromJson(json, SearchViewResponse.SpotDeatilHotelListBean.class);
                listBeans.add(hotelListBean1);
            }
            spotListBean = listBeans;
        }
        dataBinding.searchRl.setVisibility(View.GONE);
        dataBinding.flexboxLayout.setVisibility(View.GONE);
        searchViewRv.setVisibility(View.VISIBLE);
        dataBinding.searchView.setVisibility(View.VISIBLE);
        searchViewAdapter.setHotelData(hotelListBean);
        searchViewAdapter.notifyDataSetChanged();
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.search_hotel) {
            searchViewAdapter.setHotelData(hotelListBean);
            searchViewAdapter.notifyDataSetChanged();
        } else if (id == R.id.ser_all_ser) {
            searchViewAdapter.setHotelData(spotListBean);
            searchViewAdapter.notifyDataSetChanged();
        } else if (id == R.id.back) {
            finish();
        } else if (id == R.id.query_btn) {
            keyWord = dataBinding.searchEt.getText().toString().trim();
            if (TextUtils.isEmpty(keyWord)) {
                Toast.makeText(this, "请输入搜索内容", Toast.LENGTH_SHORT).show();
            } else {
                insertData(keyWord);
            }
        } else if (id == R.id.search_del) {
            showDelDialog();
        }
    }

    private void insertData(String keyWord) {
        notes = noteDao.loadAll();
//        searchDaos = searchDaoDao.loadAll();
        if (notes != null ) {
            flexboxLayout.removeAllViews();

            int i = 0;
            for (i = 0; i < notes.size(); i++) {
                String recordLog = notes.get(i).getName();
                if (recordLog.equals(keyWord)) {
                    break;

                }
            }

            if (i == notes.size()) {
                Note note = new Note(null, keyWord);
                note.setName(keyWord);
                noteDao.insert(note);
            }
            reFreshData();
            Bundle bundle = new Bundle();
            bundle.putString("key",keyWord);
            bundle.putString("value",value);
            JumpUtils.jumptoNatvie(this,"searchlist",0,bundle);

        }
    }

    private void showDelDialog() {
        final TwoButtonDialog dialog = new TwoButtonDialog(this, "确认删除全部历史记录吗");
        dialog.setOnOkClickListener(new TwoButtonDialog.OnOkClickListener() {
            @Override
            public void onOkClick() {
                dialog.cancel();
            }
        });
        dialog.setOnCancelClickListener(new TwoButtonDialog.OnCancelClickListener() {
            @Override
            public void onCancelClick() {
                noteDao.deleteAll();
                dialog.cancel();
                reFreshData();
            }
        });
        dialog.show();
    }

}
